package cn.tnar.parkservice.controller.customer;

import cn.tnar.parkservice.config.Constant;
import cn.tnar.parkservice.model.dto.TParkCalendarDto;
import cn.tnar.parkservice.model.dto.TParkCalendarDto1;
import cn.tnar.parkservice.model.entity.TParkCalendar;
import cn.tnar.parkservice.model.request.MemberGoupReqParam;
import cn.tnar.parkservice.service.ITParkCalendarService;
import cn.tnar.parkservice.service.MqService;
import cn.tnar.parkservice.util.common.ResultCode;
import cn.tnar.parkservice.util.common.ResultJson;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

/**
 * @author dzx
 * @ClassName:
 * @Description:
 * @date 2019年09月04日 19:53:27
 */
@RestController
@RequestMapping("/service/tParkCalendar")
@Slf4j
@Api(tags = "节假日配置TParkCalendarController")
public class TParkCalendarController {

    @Autowired
    @Qualifier("tParkCalendarServiceImpl")
    private ITParkCalendarService itParkCalendarService;
    private static final ResultJson RESULT_JSON = new ResultJson();

    @Autowired
    private MqService mqService;


    @PostMapping("/insert")
    @ApiOperation("新增单个停车节假日")
    public ResultJson insert(@RequestBody String json) {
        try {
            TParkCalendar tParkCalendar = JSON.parseObject(json, TParkCalendar.class);
            boolean save = itParkCalendarService.save(tParkCalendar);
            if (save) {
                return getSuccessResultJson(true);
            } else {
                return getFailResultJson(false);
            }
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }


    @PostMapping("/update")
    @ApiOperation("更新单个停车节假日")
    public ResultJson update(@RequestBody String json) {
        try {
            TParkCalendar tParkCalendar = JSON.parseObject(json, TParkCalendar.class);
            boolean update = itParkCalendarService.updateById(tParkCalendar);
            if (update) {
                return getSuccessResultJson(true);
            } else {
                return getFailResultJson(false);
            }
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }

    /**
     * 批量设置节假日日历
     *
     * @param json
     * @return ResultJson
     */
    @PostMapping("/batchInsert")
    @ApiOperation("批量新增停车节假日")
    @Transactional
    public ResultJson batchInsert(@RequestBody String json) {
        try {
            TParkCalendarDto tParkCalendarDto = JSON.parseObject(json, TParkCalendarDto.class);
            Long agentId = tParkCalendarDto.getAgentId(); //8010000122418
            String parkCode = tParkCalendarDto.getParkCode(); //110228200003
            String holidays = tParkCalendarDto.getHolidays(); //20190203,20190809
            String holidayName = tParkCalendarDto.getHolidayName();
            if (StringUtils.isNotBlank(holidays)) {
                String[] holidayArray = holidays.split(",|，");
                for (String holiday : holidayArray) {
                    Integer int_holiday = Integer.valueOf(holiday);
                    TParkCalendar tParkCalendar = new TParkCalendar()
                            .setNodeId(1)
                            .setHoliday(int_holiday)
                            .setAgentId(agentId)
                            .setParkCode(parkCode)
                            .setRegionCode("")
                            .setHolidayName(holidayName);
                    //判断当前停车场，当前日期是否存在
                    QueryWrapper<TParkCalendar> queryWrapper = new QueryWrapper<TParkCalendar>();
                    queryWrapper.eq("park_code", parkCode).eq("holiday", int_holiday);
                    TParkCalendar one = null;
                    try {
                        one = itParkCalendarService.getOne(queryWrapper, true);
                    } catch (Exception e) {
                        log.error("停车场" + parkCode + "同一日期" + int_holiday + "只能配置一次节假日", e);
                        return getFailResultJson("停车场" + parkCode + "同一日期" + int_holiday + "只能配置一次节假日");
                    }
                    if (one == null) {
                        boolean save = itParkCalendarService.save(tParkCalendar);
                        if (save) {
                            TParkCalendarDto1 tParkCalendarDto1 = new TParkCalendarDto1();
                            tParkCalendarDto1.setStatus(0);//通知车道当前状态是新增节假日
                            BeanUtils.copyProperties(tParkCalendar, tParkCalendarDto1);
                            mqService.convertAndSend(Constant.EXCHANGE_NAME, Constant.PARKCALENDAR_QUEUENAME_PREFIX + parkCode, JSON.toJSONString(tParkCalendarDto1));
                        }
                    }
                }
            }
            return getSuccessResultJson(true);
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }


    /**
     * 根据停车场编号查询节假日
     *
     * @param json
     * @return ResultJson
     */
    @PostMapping("/selectByParkCode")
    @ApiOperation("根据停车场编号查询节假日")
    public ResultJson selectByParkCode(@RequestBody String json) {
        try {
            MemberGoupReqParam reqParam = JSON.parseObject(json, MemberGoupReqParam.class);
            String parkCode = reqParam.getParkCode();
            QueryWrapper<TParkCalendar> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("park_code", parkCode);
            List<TParkCalendar> list = itParkCalendarService.list(queryWrapper);
            return getSuccessResultJson(list);
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }


    /**
     * 批量删除当前停车场的日历节假日
     *
     * @param json
     * @return ResultJson
     */
    @PostMapping("/deleteByIds")
    @ApiOperation("批量删除当前停车场的日历节假日")
    public ResultJson deleteByIds(@RequestBody String json) {
        try {
            MemberGoupReqParam reqParam = JSON.parseObject(json, MemberGoupReqParam.class);
            String ids = reqParam.getIds();
            String parkCode = reqParam.getParkCode();
            if (StringUtils.isNotBlank(ids)) {
                QueryWrapper<TParkCalendar> queryWrapper = new QueryWrapper<>();
                queryWrapper.in("id", ids);
                List<TParkCalendar> list = itParkCalendarService.list(queryWrapper);

                List<String> idList = Arrays.asList(ids.split(",|，"));
                boolean result = itParkCalendarService.removeByIds(idList);
                if (result) {
                    for (TParkCalendar tParkCalendar : list) {
                        TParkCalendarDto1 tParkCalendarDto1 = new TParkCalendarDto1();
                        BeanUtils.copyProperties(tParkCalendar, tParkCalendarDto1);
                        tParkCalendarDto1.setStatus(1);//通知车道删除节假日
                        mqService.convertAndSend(Constant.EXCHANGE_NAME, Constant.PARKCALENDAR_QUEUENAME_PREFIX + parkCode, JSON.toJSONString(tParkCalendarDto1));
                    }
                    return getSuccessResultJson(true);
                } else {
                    return getFailResultJson(false);
                }
            } else {
                return getFailResultJson("没有选择删除项");
            }
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }


    /**
     * 获取失败返回消息体
     *
     * @param data
     * @return
     */
    private ResultJson getFailResultJson(Object data) {
        return RESULT_JSON.setCode(ResultCode.FAIL)
                .setMsg(ResultCode.FAIL_MSG).setData(data);
    }

    /**
     * 获取成功返回消息体
     *
     * @param data
     * @return
     */
    private ResultJson getSuccessResultJson(Object data) {
        return RESULT_JSON.setCode(ResultCode.SUCCESS)
                .setMsg(ResultCode.SUCCESS_MSG).setData(data);
    }


}
